function DB.RetrieveMoney(ply)
	if not ValidEntity(ply) then return 0 end
	
	local r = ply.MoneyInBackPack
	
	if not r then 
		r = 0 
	end
	
	ply:SetNWInt("money", math.floor(r))
	return r
end

function DB.StoreMoney(ply, amount)
	if not ValidEntity(ply) then return end
	if amount < 0  then return end
	ply.MoneyInBackPack = amount
	ply:SetNWInt("money", math.floor(amount))
end

function DB.StoreMoneyInBank(ply, amount)
	if not ValidEntity(ply) then return end
	if amount < 0  then return end
	local steamID = ply:SteamID()
	local r = sql.QueryValue("SELECT amount FROM darkrp_wallets WHERE steam = " .. sql.SQLStr(steamID) .. ";")
	if r then
		sql.Query("UPDATE darkrp_wallets SET amount = " .. math.floor(amount) .. " WHERE steam = " .. sql.SQLStr(steamID) .. ";")
	else
		sql.Query("INSERT INTO darkrp_wallets VALUES(" .. sql.SQLStr(steamID) .. ", " .. math.floor(amount) .. ");")
	end
	ply:SetNWInt("BankMoney", math.floor(amount))
end

function DB.RetrieveMoneyFromBank(ply)
	if  !ply:IsPlayer() then 
		return 0 
	end
	local steamID = ply:SteamID()
	local startingAmount = 500
		
	local r = sql.QueryValue("SELECT amount FROM darkrp_wallets WHERE steam = " .. sql.SQLStr(ply:SteamID()) .. ";")
	if r then
		ply:SetNWInt("BankMoney", math.floor(r))
		return tonumber(r)
	else
		-- No record yet, setting starting cash to 500
		DB.StoreMoneyInBank(ply, startingAmount)
		return startingAmount
	end
end

function DropMoney(ply, args)
	if args == "" then return "" end
	
	if not tonumber(args) then
		return ""
	end
	local amount = math.floor(tonumber(args))

	if amount <= 0 then
		return ""
	end

	if not ply:CanAfford(amount) then
		Notify(ply, 1, 4, "Can not afford this!")
		return ""
	end

	ply:AddMoney(-amount)

	local trace = {}
	trace.start = ply:EyePos()
	trace.endpos = trace.start + ply:GetAimVector() * 85
	trace.filter = ply

	local tr = util.TraceLine(trace)
	local moneybag = ents.Create("prop_physics")
	moneybag:SetModel("models/props/cs_assault/money.mdl")
	moneybag:SetNWString("Owner", "Shared")
	moneybag:SetPos(tr.HitPos)
	moneybag.nodupe = true
	moneybag:Spawn()
	moneybag:GetTable().MoneyBag = true
	moneybag:GetTable().Amount = amount

	return ""
end

local meta = FindMetaTable("Player")

function meta:AddMoneyToBank(amount)
	DB.StoreMoneyInBank(self, DB.RetrieveMoneyFromBank(self) + math.floor(amount))
end

function meta:GetMoneyOfBank()
	if IsValid(self) then
		return DB.RetrieveMoneyFromBank(self)
	else
		return 0
	end
end

